package dao.impl;

import dao.WarehouseDao;
import po.Warehouse;
import util.BaseDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class WarehouseImpl implements WarehouseDao {

    public List<Warehouse> selectWarehouse(String sql) {
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            //获取数据库连接
            con= BaseDao.getConnection();
            ps=con.prepareStatement(sql);
            System.out.println("ps="+ps);
            rs=ps.executeQuery();
            List<Warehouse> list =new ArrayList<>();
            while (rs.next()){
                Warehouse warehouse=new Warehouse();
                warehouse.setWarehouseId(rs.getString("warehouse_id"));
                warehouse.setGoodId(rs.getString("good_id"));
                warehouse.setGoodName(rs.getString("good_name"));
                warehouse.setType(rs.getString("type"));
                warehouse.setCount(rs.getInt("count"));
                warehouse.setCost(rs.getDouble("cost"));
                warehouse.setImStorage(rs.getDate("im_storage"));
                list.add(warehouse);
            }
            return list;
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(con,ps,rs);
        }
        return null;
    }

    @Override
    public List<String> selectWarehouseId() {
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        try{
            con= BaseDao.getConnection();
            ps=con.prepareStatement("select DISTINCT warehouse_id from warehouse");
            rs=ps.executeQuery();
            List<String> list =new ArrayList<>();
            while (rs.next()){
                list.add(rs.getString("warehouse_id"));
            }
            return list;
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(con,ps,rs);
        }
        return null;
    }

    @Override
    public void addWarehouse(Warehouse warehouse) {
        String sql = "insert into warehouse values (?,?,?,?,?,?,now())";
        List<Object> list = new ArrayList<>();
        list.add(warehouse.getWarehouseId());
        list.add(warehouse.getGoodName());
        list.add(warehouse.getGoodId());
        list.add(warehouse.getType());
        list.add(warehouse.getCount());
        list.add(warehouse.getCost());

        System.out.println(sql);
        System.out.println("id="+warehouse.getWarehouseId());
        BaseDao.addUpdateDelete(sql, list.toArray());
    }

}
